<template>
  <div class="space-y-4">
    <div class="card flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
      <input type="date" class="input flex-1" v-model="date" @change="load" />
      <select class="input flex-1" v-model="filter" @change="load">
        <option value="ALL">全部</option>
        <option value="FEEDING">喂奶</option>
        <option value="DIAPER">尿布</option>
        <option value="SLEEP">睡眠</option>
        <option value="CRY">哭闹</option>
      </select>
      <button class="btn-primary" @click="load">刷新</button>
    </div>

    <div v-if="loading" class="text-center text-gray-500">加载中...</div>
    <div v-else class="space-y-3">
      <div v-if="displayItems.length === 0" class="text-center text-gray-500">暂无记录</div>
      <div v-for="item in displayItems" :key="item.key" class="card">
        <div class="text-sm text-gray-500">{{ item.time }} · {{ item.typeText }}</div>
        <div class="mt-1">{{ item.content }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { useUserStore } from '../stores/user';
import { type TimelineByDatePayload, API_CONFIG } from '../services/api';

// 临时解决方案：直接定义函数
async function timelineByDate(payload: TimelineByDatePayload) {
  const token = localStorage.getItem('auth_token');
  console.log('Timeline timelineByDate - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/timeline/by-date`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

type TimelineType = 'FEEDING' | 'DIAPER' | 'SLEEP' | 'CRY';

const userStore = useUserStore();
const date = ref<string>(new Date().toLocaleDateString('en-CA'));
const filter = ref<TimelineType | 'ALL'>('ALL');
const loading = ref(false);
const rawItems = ref<
  Array<{ type: TimelineType; eventTime: string; data: any }>
>([]);

const displayItems = computed(() => {
  const arr = (filter.value === 'ALL'
    ? rawItems.value
    : rawItems.value.filter((i) => i.type === filter.value))
    .map((i, idx) => {
      return {
        key: `${i.type}-${idx}-${i.eventTime}`,
        time: formatTime(i.eventTime),
        typeText: mapTypeText(i.type),
        content: summarize(i)
      };
    });
  return arr;
});

function mapTypeText(t: TimelineType) {
  switch (t) {
    case 'FEEDING': return '喂奶';
    case 'DIAPER': return '尿布';
    case 'SLEEP': return '睡眠';
    case 'CRY': return '哭闹';
  }
}

function summarize(i: { type: TimelineType; data: any }) {
  if (i.type === 'FEEDING') {
    const d = i.data;
    return d.feedingType === 'FORMULA'
      ? `配方奶 ${d.formulaMl ?? '-'} ml`
      : `母乳 左${d.leftMinutes ?? 0}分 右${d.rightMinutes ?? 0}分`;
  }
  if (i.type === 'DIAPER') return `${mapDiaper(dSafe(i).diaperType)}`;
  if (i.type === 'SLEEP') {
    const d = i.data;
    const start = formatTime(d.sleepStart);
    const end = d.sleepEnd ? formatTime(d.sleepEnd) : '至今';
    return `睡眠 ${start} - ${end}`;
  }
  if (i.type === 'CRY') {
    const d = i.data;
    return `哭闹 ${formatTime(d.startTime)}${d.endTime ? ' - ' + formatTime(d.endTime) : ''}`;
  }
  return '';
}

function dSafe(i: any) { return i.data || {}; }
function mapDiaper(t: string) { return t === 'WET' ? '清尿' : t === 'DIRTY' ? '便便' : '混合'; }
function formatTime(iso: string) { const d = new Date(iso); return d.toTimeString().slice(0,5); }

async function load() {
  console.log('Timeline load - currentBabyId:', userStore.currentBabyId);
  console.log('Timeline load - currentUser:', userStore.currentUser);
  console.log('Timeline load - familyBabies:', userStore.familyBabies);
  
  if (!userStore.currentBabyId) {
    console.log('Timeline: 没有选择宝宝，无法加载时光轴');
    return;
  }
  
  try {
    loading.value = true;
    console.log('Timeline: 开始加载时光轴数据...');
    const payload: TimelineByDatePayload = { babyId: userStore.currentBabyId, date: date.value };
    const res = await timelineByDate(payload);
    rawItems.value = Array.isArray(res) ? res : [];
    console.log('Timeline: 时光轴数据加载成功', rawItems.value);
  } catch (error) {
    console.error('Timeline: 加载时光轴失败', error);
  } finally {
    loading.value = false;
  }
}

// 监听宝宝切换，重新加载数据
watch(() => userStore.currentBabyId, () => {
  if (userStore.currentBabyId) {
    load();
  }
});

onMounted(load);
</script>

<style scoped></style>